package com.xxx.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.text.MessageFormat;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.code.kaptcha.Producer;
import com.xxx.constant.RedisConstants;
import com.xxx.dto.ResponseDTO;
import com.xxx.util.CommonUtil;
import com.xxx.util.JedisUtil;

/**
 * 图片验证码相关 Controller
 */
@Controller
public class KaptchaController {

    private static final Logger logger = LoggerFactory.getLogger(KaptchaController.class);

    // 图片验证码cookie名称
    private static final String COOKIE_NAME_CAPTCHACODE = "captchaCode";

    // 图片验证码过期时间
    private static final int EXPIRE_TIME_CAPTCHACODE = 60 * 10; // 10分钟

    @Autowired
    private Producer kaptcha; // google图片验证码工具

    /**
     *  获取图片验证码接口 getCaptchaImg
     */
    @RequestMapping("/getCaptchaImg")
    public ModelAndView getCaptchaImg(HttpServletRequest request, HttpServletResponse response) {
        logger.info("enter method getCaptchaImg().");
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 获取图片验证码字符串
        String capText = kaptcha.createText();
        logger.info("getCaptchaImg | 生成的图片验证码内容为：{}", capText);

        // 把图片验证码的值放入到redis和cookie中
        String uuid = CommonUtil.getUUID();
        String redisKey = MessageFormat.format(RedisConstants.REDIS_KEY_VERICODE_IMG, uuid);
        JedisUtil.setex(redisKey, capText, EXPIRE_TIME_CAPTCHACODE); // 设置图片验证码过期时间
        Cookie cookie = new Cookie(COOKIE_NAME_CAPTCHACODE, uuid);
        cookie.setMaxAge(EXPIRE_TIME_CAPTCHACODE); // 设置会话生命周期
        response.addCookie(cookie);

        // 生成验证码图片
        BufferedImage bi = kaptcha.createImage(capText);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
        } catch (Exception e) {
            logger.error("getCaptchaImg | 生成验证码，io流写文件异常:" + e);
        } finally {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                logger.error("getCaptchaImg | 生成验证码，关闭流异常：" + e);
            }
        }
        return null;
    }

    /**
     * 验证图片验证码是否正确接口 chkCaptchaImg
     */
    @RequestMapping("/chkCaptchaImg")
    @ResponseBody
    public ResponseDTO chkCaptchaImg(HttpServletRequest request, HttpServletResponse response,
    		@CookieValue(value=COOKIE_NAME_CAPTCHACODE) Cookie cookie) {
        logger.info("enter method chkCaptchaImg().");

        String paramImgVeriCode = request.getParameter("imgVeriCode");
        if (StringUtils.isBlank(paramImgVeriCode) || cookie==null) {
            return ResponseDTO.builtSuccess("false");
        }
        logger.info("chkCaptchaImg | paramImgVeriCode:{}", paramImgVeriCode);
        boolean veryImageCodeRet = this.verifyImageCode(request, paramImgVeriCode, cookie);
        return veryImageCodeRet ? ResponseDTO.builtSuccess("true") : ResponseDTO.builtSuccess("false");
    }

    /**
     * 校验图片验证码
     * @param request
     * @param imgVeriCode
     * @param cookie
     * @return
     */
    private boolean verifyImageCode(HttpServletRequest request, String imgVeriCode, Cookie cookie) {
        // 从cookie里获取图片验证码，然后和redis中的比较
		String uuid = cookie.getValue();
		if (!StringUtils.isBlank(uuid)) {
			String redisKey = MessageFormat.format(RedisConstants.REDIS_KEY_VERICODE_IMG, uuid);
			String correctCode = JedisUtil.get(redisKey);
			JedisUtil.del(redisKey); // 删除key，验证码只能被使用1次，无论验证是否通过
			if (imgVeriCode.equalsIgnoreCase(correctCode)) { // 传过来的验证码和redis中的验证码不区分大小写匹配成功
				return true;
			} else {
				logger.error("veryImageCode | imgVeriCode.equalsIgnoreCase(correctCode)==false."
						+ " imgVeriCode:{}, correctCode:{}", imgVeriCode, correctCode);
			}
		}
        return false;
    }

}
